package com.awei.project.controller;

import com.awei.project.common.BaseResponse;
import com.awei.project.common.ErrorCode;
import com.awei.project.common.ResultUtils;
import com.awei.project.exception.BusinessException;
import com.awei.project.model.dto.teamRequest.*;
import com.awei.project.model.entity.Team;
import com.awei.project.model.entity.User;
import com.awei.project.model.entity.UserTeam;
import com.awei.project.model.enums.TeamStatusEnum;
import com.awei.project.model.vo.TeamUserVo;
import com.awei.project.service.TeamService;
import com.awei.project.service.UserService;
import com.awei.project.service.UserTeamService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 小维哥
 * @version 1.2
 */
@RestController
@Slf4j
@RequestMapping("/team")
public class TeamController {
        @Resource
        TeamService teamService;
        @Resource
        UserService userService;
        @Resource
        UserTeamService userTeamService;
        @ApiOperation("创建队伍")
        @PostMapping("/add")
        public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
                User loginUser = userService.getLoginUser(request);
                if (teamAddRequest == null || loginUser == null) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                long teamId = teamService.addTeam(teamAddRequest, loginUser);
                return ResultUtils.success(teamId);
        }

        @ApiOperation("队伍的解散")
        @PostMapping("/delete")
        public BaseResponse<Boolean> DeleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
                if (deleteRequest == null || deleteRequest.getTeamId() <= 0) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                long id = deleteRequest.getTeamId();
                User loginUser = userService.getLoginUser(request);
                Boolean b = teamService.deleteTeam(id, loginUser);
                return ResultUtils.success(b);
        }

        @ApiOperation("队伍的修改")
        @PostMapping("/update")
        public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
                if (teamUpdateRequest == null) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
                }
                System.out.println(teamUpdateRequest);
                User loginUser = userService.getLoginUser(request);
                Boolean b = teamService.updateTeam(teamUpdateRequest, loginUser);
                return ResultUtils.success(b);
        }

        @ApiOperation("id获取队伍基本信息")
        @GetMapping("/gets")
        public BaseResponse<Team> OldgetTeamById(long id) {
                if (id <= 0) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                Team team = teamService.getById(id);
                if (team == null) {
                        throw new BusinessException(ErrorCode.NULL_ERROR);
                }
                return ResultUtils.success(team);
        }

        /**
         * 根据 id 查询队伍
         * @param id
         * @return
         */
        @ApiOperation("id获取队伍的用户信息")
        @GetMapping("/get")
        public BaseResponse<TeamUserVo> getTeamById(long id,HttpServletRequest request){
                if (id <= 0) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                //根据队伍Id，查team
                TeamSearchRequest teamQuery = new TeamSearchRequest();
                teamQuery.setId(id);
                List<TeamUserVo> teamList = teamService.listOtherOrMyTeam(teamQuery, true,request);
                if (CollectionUtils.isEmpty(teamList)) {
                        throw new BusinessException(ErrorCode.NULL_ERROR);
                }
                //防止查到多个队伍，直接拿到首个
                TeamUserVo team = teamList.get(0);
                if (team == null) {
                        throw new BusinessException(ErrorCode.NULL_ERROR);
                }
                //根据队伍Id，查询user_team表，获取加入的用户
                List<User> joinUser = teamService.listJoinUsers(team.getId());
                team.setJoinUsers(joinUser);
                return ResultUtils.success(team);
        }


        //todo 查询的分页栏,暂时和前端的联调出现了一些问题
        @ApiOperation("查询数据的大小,分页栏专用")
        @GetMapping("/list/simple/page")
        public BaseResponse<Page<Team>> listTeamsByPage( TeamSearchRequest teamQuery)   {
                if (teamQuery == null) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                Team team = new Team();
                BeanUtils.copyProperties(teamQuery, team);
                Page<Team> page = new Page<>(teamQuery.getPageSize(), teamQuery.getPageSize());
                QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
                Page<Team> resultPage = teamService.page(page, queryWrapper);
                return ResultUtils.success(resultPage);
        }

        /**
         *      分页获取队伍：仅传入分页值pageNum ,pageSize.和队伍状态
         *      更具特性获取队伍：传入searchText和名字查询队伍
         * @param teamQuery
         * @param request
         * @return
         */
        @ApiOperation("分页获取数据")
        @GetMapping("/list/page")
        public BaseResponse<Page<TeamUserVo>> listTeamsByPage(TeamSearchRequest teamQuery, HttpServletRequest request){
                if (teamQuery == null){
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                //前端数据的转换
                Long pageNum = teamQuery.getPageNum();
                if(pageNum!=null&&pageNum>0){
                        teamQuery.setCurrent(pageNum);
                }
                //拿到当前用户的id
                User loginUser = userService.getLoginUser(request);
                Long userId = loginUser.getId();
                Team team = new Team();
                BeanUtils.copyProperties(teamQuery, team);
                //获取信息，分页队伍
                Page<Team> page = new Page<>(teamQuery.getCurrent(), teamQuery.getPageSize());
                QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
                Integer status = teamQuery.getStatus();
                //获取队伍当前状态
                TeamStatusEnum statusEnum = TeamStatusEnum.getValues(status);
                //默认查询队伍的状态为公开
                if (statusEnum == null){
                        statusEnum = TeamStatusEnum.PUBLIC_TEAM;
                }
                queryWrapper.eq("status", statusEnum.getValue());
               //排除过期时间 qw.and(q -> q.gt("expireTime", new Date()).or().isNull("expireTime"));
                queryWrapper.and(qw->qw.gt("expireTime",new Date()).or().isNull("expireTime"));
                String searchText = teamQuery.getSearchText();
                if (StringUtils.isNotBlank(searchText)){
                        queryWrapper.and(qw -> qw.like("name", searchText)
                                .or().like("description", searchText));
                }
                // Page<Team> teamListByPage 转换为  Page<TeamUserVo> teamUserVoPage，后续进行修改
                Page<Team> teamListByPage = teamService.page(page, queryWrapper);
                Page<TeamUserVo> teamUserVoPage = new Page<>();
                teamUserVoPage.setTotal(teamListByPage.getTotal());
                teamUserVoPage.setCurrent(teamListByPage.getCurrent());
                teamUserVoPage.setPages(teamListByPage.getPages());
                teamUserVoPage.setSize(teamListByPage.getSize());
                //对分页数据的records进行校验
                List<TeamUserVo> TUrecords =new ArrayList<>();
                List<Team> records = teamListByPage.getRecords();
                for (int i = 0; i < records.size(); i++) {
                        Team teamPage = records.get(i);
                        TeamUserVo teamUserVo=new TeamUserVo(); //展示的队伍
                        BeanUtils.copyProperties(teamPage,teamUserVo);
                        //队伍id
                        Long teamId = teamUserVo.getId();
                        //获取已加入队伍人数
                        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
                        userTeamQueryWrapper.eq("teamId", teamId);
                        long hasJoinNum = userTeamService.count(userTeamQueryWrapper);
                        //放入 team的 hasJoinNum 字段
                        teamUserVo.setHasJoinNum((int)hasJoinNum);
                        userTeamQueryWrapper = new QueryWrapper<>();
                        userTeamQueryWrapper.eq("teamId", teamPage.getId());
                        userTeamQueryWrapper.eq("userId", userId);
                        List<UserTeam> list = userTeamService.list(userTeamQueryWrapper);
                        //判断是否为创建队伍的本人
                        if (list.size() != 0){
                                teamUserVo.setHasJoin(true);
                        }
                        TUrecords.add(teamUserVo);
                }
                if(TUrecords.size()<=0){
                        throw new BusinessException(ErrorCode.NULL_ERROR,"数据为空");
                }
                teamUserVoPage.setRecords(TUrecords);
                return ResultUtils.success(teamUserVoPage);
        }

        @ApiOperation("队伍的加入")
        @PostMapping("/join")
        public BaseResponse<Boolean> JoinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
                if (teamJoinRequest == null) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                User loginUser = userService.getLoginUser(request);
                Boolean b = teamService.joinTeam(teamJoinRequest, loginUser);
                return ResultUtils.success(b);
        }

        @ApiOperation("队伍的退出")
        @PostMapping("/quit")
        public BaseResponse<Boolean> QuitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
                if (teamQuitRequest == null) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                User loginUser = userService.getLoginUser(request);
                Boolean b = teamService.quitTeam(teamQuitRequest, loginUser);
                return ResultUtils.success(b);
        }


        //1 获取我创建的队伍
        @ApiOperation("获取自己创建的队伍")
        @GetMapping("/list/my/create")
        public BaseResponse<List<TeamUserVo>> listMyCreateTeams(TeamSearchRequest teamQuery, HttpServletRequest request) {
                if (teamQuery == null) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                User loginUser = userService.getLoginUser(request);
                teamQuery.setUserId(loginUser.getId());
                List<TeamUserVo> teamList = teamService.listOtherOrMyTeam(teamQuery, true,request);
                return ResultUtils.success(teamList);
        }

        // 2 获取我加入的队伍
        @ApiOperation("获取自己加入的队伍")
        @GetMapping("/list/my/join")
        public BaseResponse<List<TeamUserVo>> listMyJoinTeams(TeamSearchRequest teamQuery, HttpServletRequest request) {
                if (teamQuery == null) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                User loginUser = userService.getLoginUser(request);
                QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("userId", loginUser.getId());
                List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
                // 取出不重复的队伍 id
                Map<Long, List<UserTeam>> listMap = userTeamList.stream()
                        .collect(Collectors.groupingBy(UserTeam::getTeamId));
                List<Long> idList = new ArrayList<>(listMap.keySet());
                teamQuery.setIdList(idList);
                List<TeamUserVo> teamList = teamService.searchTeam(teamQuery,true,request);
                return ResultUtils.success(teamList);
        }

}
